package orch

import (
	"github.com/hashicorp/hcl/v2"
	"github.com/hashicorp/hcl/v2/hclparse"
	"github.com/ihaiker/tfwrapper/internal/util"
	"path/filepath"
)

// parseTerraformVariables 解析terraform源文件的variable
func parseTerraformVariables(sourcePath string) (vars []string, diags hcl.Diagnostics) {
	names := util.ListTerraformFile(sourcePath)
	parser := hclparse.NewParser()
	files := make([]*hcl.File, 0)
	for _, name := range names {
		file, dig := parser.ParseHCLFile(filepath.Join(sourcePath, name))
		if dig.HasErrors() {
			diags = diags.Extend(dig)
		}
		files = append(files, file)
	}
	body := hcl.MergeFiles(files)
	ctx, _, dig := body.PartialContent(&hcl.BodySchema{
		Blocks: []hcl.BlockHeaderSchema{
			{
				Type:       "variable",
				LabelNames: []string{"name"},
			},
		},
	})
	if dig.HasErrors() {
		diags = diags.Extend(dig)
	}
	for _, block := range ctx.Blocks {
		vars = append(vars, block.Labels[0])
	}
	return
}
